package cn.wizzer.app.web.commons.ext.websocket.filter;

import cn.wizzer.app.user.modules.models.User;
import cn.wizzer.app.user.modules.models.enums.EquipmentEnum;
import cn.wizzer.app.user.modules.models.vo.ChatUserVO;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.app.web.commons.ext.websocket.main.action.BaseNettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.base.NettyCache;
import cn.wizzer.app.web.commons.ext.websocket.main.base.NettyRouter;
import cn.wizzer.app.web.commons.ext.websocket.main.filter.BaseNettyFilter;
import cn.wizzer.app.web.commons.ext.websocket.main.filter.NettyFilter;
import cn.wizzer.app.web.commons.utils.TokenUtil;
import cn.wizzer.framework.util.Result;
import cn.wizzer.framework.util.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.commons.lang3.EnumUtils;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

/**
 * 登录认证
 */
//支持集成|spring.@Baen
@IocBean
@NettyFilter
public class TokenFilter extends BaseNettyFilter {
    @Inject
    private TokenUtil tokenUtil;

    @Inject
    @Reference
    private UserService userService;

    @Override
    public Result doFilter(NettyRouter router, BaseNettyAction action) {
        String appid = router.getParams().getString("appid");
        String token = router.getParams().getString("token");
        if (Strings.isBlank(appid) || Strings.isBlank(token)) {
            return Result.error().addCode(-2);
        }
        // 非临时的
        if (!appid.contains("TEMPID")) {
            boolean useful = tokenUtil.verifyToken(appid, token);
            if (!useful) {
                return Result.error().addCode(-2);
            }
        }

        //缓存用户信息到缓存区以便查询
        ChatUserVO chatUserVO = NettyCache.globalGet(appid);
        // 没有连接的时候会新建一个，如果原来有就会保留原来的，会有BUG
        // 处理
        // 1、登录的时候，原来的连接得销毁，不能每次都销毁？根据什么来判断一下，是否新建立
        // 账号重新登录，原来的WSOCKET要先全部销毁
        if (chatUserVO == null) {
            User fetch = userService.fetch(appid);
            chatUserVO = JSONUtil.parseJavaBean(ChatUserVO.class, fetch);

            chatUserVO.setPassword(null);
            chatUserVO.setSalt(null);
            chatUserVO.setChannel(router.getIncome());
            // 覆盖得处理
            NettyCache.globalPut(appid, chatUserVO);
            NettyCache.localSet(router.getIncome(), "currentUserId", appid);
        }

        return null;
    }
}
